package com.electric.qrapp.entity.init

import android.content.Context
import com.electric.qrapp.utils.system.showLog
import com.tencent.smtt.export.external.TbsCoreSettings
import com.tencent.smtt.sdk.QbSdk
import com.tencent.smtt.sdk.TbsDownloader
import com.tencent.smtt.sdk.TbsListener

/**
 *@author created by WA03675
 *@date  2022-04-02 09:12
 *@des
 */
object X5init {

    private var resultListener: ((success: Boolean) -> Unit)? = null
    var installerCode = 0


    fun init(context: Context) {
        initOptimize()
        initSdk(context)
    }

    private fun initOptimize() {
        val map = HashMap<String, Any>()
        map[TbsCoreSettings.TBS_SETTINGS_USE_SPEEDY_CLASSLOADER] = true
        map[TbsCoreSettings.TBS_SETTINGS_USE_DEXLOADER_SERVICE] = true
        QbSdk.initTbsSettings(map)
    }


    private fun initSdk(context: Context) {

        QbSdk.setDownloadWithoutWifi(true)


        QbSdk.setTbsListener(
            object : TbsListener {
                override fun onDownloadFinish(i: Int) {
                    //下载结束时的状态，下载成功时errorCode为100,其他均为失败，外部不需要关注具体的失败原因
                    showLog("下载结束, ${if (i == 100) "成功" else "失败"}")
                }

                override fun onInstallFinish(i: Int) {
                    //安装结束时的状态，安装成功时errorCode为200,其他均为失败，外部不需要关注具体的失败原因
                    showLog("安装结束, ${if (i == 200) "成功" else "失败"}")
                    resultListener?.invoke(i == 200)
                    installerCode = i

                }

                override fun onDownloadProgress(i: Int) {
                    //下载过程的通知，提供当前下载进度[0-100]
                    showLog("当前下载进度 $i")
                }
            })


        //x5内核初始化接口
        QbSdk.initX5Environment(context, object : QbSdk.PreInitCallback {
            override fun onViewInitFinished(arg0: Boolean) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                showLog("x5内核 ${if (arg0) "加载成功!!" else "加载失败!!"}")
            }

            override fun onCoreInitFinished() {
            }
        })
    }

    //需要重新下载
    fun resetDownload(context: Context, resultListener: ((success: Boolean) -> Unit)) {
        this.resultListener = resultListener
        reset(context)
    }

    private fun reset(context: Context) {
        QbSdk.reset(context)
        TbsDownloader.startDownload(context)
    }
}